package com.maidada.codesharebackend.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.maidada.codesharebackend.util.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户上下文拦截器
 * 用于在请求处理前设置用户ID，请求处理后清除
 *
 * @author wulinxuan
 */
@Slf4j
@Component
public class UserContextInterceptor implements HandlerInterceptor {

    /**
     * 请求处理前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从 Sa-Token session 中获取当前登录用户 ID
        try {
            if (StpUtil.isLogin()) {
                Long userId = StpUtil.getLoginIdAsLong();
                UserContext.setUserId(userId);
                log.debug("设置当前用户ID: {}", userId);
            }
        } catch (Exception e) {
            log.warn("获取当前登录用户ID失败: {}", e.getMessage());
        }

        return true;
    }

    /**
     * 请求完成后执行（无论是否发生异常）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清除用户ID，避免内存泄漏
        UserContext.clear();
        log.debug("清除当前用户ID");
    }
}

